package com.xiaoma.dao;

import com.xiaoma.constant.EsConstant;
import entity.Goods;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.frameworkset.elasticsearch.ElasticSearchException;
import org.frameworkset.elasticsearch.ElasticSearchHelper;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.frameworkset.elasticsearch.entity.ESDatas;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;


/**
 * @Author: xiaoma
 * @Date: 2021/7/8 14:53
 * @description:
 */
@Component
@Slf4j
public class ESDao {
   /**
    * @Description 向ES中添加商品
    * @Author Xiaoma
    * @Date 2021/8/27 10:52
    * @param goods
    * @return boolean
    **/
    public boolean productGoods(Goods goods) {
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        goods.setProductTime(time);
        ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil(EsConstant.ESMAPPER);
        try {
            clientUtil.addDocument(EsConstant.PRODUCT_INDEX, goods);
            return true;
        } catch (ElasticSearchException e) {
            log.error("es batch add error.", e);
        }
        return false;
    }

    /**
     * @Description 在ES中根据关键字检索商品
     * @Author Xiaoma
     * @Date 2021/8/27 10:52
     * @param keyword
     * @return java.util.List<entity.Goods>
     **/
    public List<Goods> SearchGoodsByKeyword(String keyword) {
        ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil(EsConstant.ESMAPPER);
        try {
            if (StringUtils.isEmpty(keyword)||StringUtils.isBlank(keyword)) {
                return clientUtil.searchList("product/_search", "queryAllBook", null, Goods.class).getDatas();
            }
            HashMap<String, String> map = new HashMap<>();
            map.put("title", keyword);
            return clientUtil.searchList("product/_search", "queryBookByTitle", map, Goods.class).getDatas();
        } catch (ElasticSearchException e) {
            log.error("es queryList error.", e);
        }
        return null;
    }

}
